package com.iwinding.ladygg.modle.db.impl;

import android.content.Context;
import android.text.TextUtils;

import com.iwinding.ladygg.modle.db.DBHelper;
import com.iwinding.ladygg.modle.db.bean.Users;
import com.iwinding.ladygg.modle.db.dao.UsersDao;

import java.util.List;

/**
 * Created by 82218 on 2017/6/22.
 */

public class UserDBHelper extends DBHelper implements DBHelper.IUserHelper {

    private static UserDBHelper userDBHelper;

    private UsersDao usersDao;

    private UserDBHelper(Context context) {
        usersDao = DBHelper.getSession(context).getUsersDao();
    }

    public static UserDBHelper getInstance(Context context) {
        if (userDBHelper == null) {
            userDBHelper = new UserDBHelper(context);
        }
        return userDBHelper;
    }


    @Override
    public List<Users> queryUsers() {
        List<Users> userses = usersDao.queryBuilder().orderAsc(UsersDao.Properties.UserId).list();
        if (userses != null && userses.size() != 0) {
            return userses;
        }
        return null;
    }

    @Override
    public void addAllUsers(List<Users> userses) {
        for (Users user:userses){
            addUser(user);
        }
    }

    public Users queryUserByGroupId(String groupId){
        List<Users> userses = usersDao.queryBuilder().where(UsersDao.Properties.GroupId.eq(groupId)).list();
        if (userses != null && userses.size() != 0) {
            return userses.get(0);
        }
        return null;
    }

    void addUser(Users user) {
        if (user == null || TextUtils.isEmpty(user.getUserId())) {
            return;
        }
        List<Users> list = usersDao.queryBuilder().where(UsersDao.Properties.UserId.eq(user.getUserId())).list();
        if (list == null || list.size() == 0) {
            usersDao.insert(user);
        } else {
            Users update = list.get(0);
            update(update, user);
            usersDao.update(update);
        }
    }

    void update(Users oldUser, Users newUser) {
        oldUser.setUserId(newUser.getUserId());
        oldUser.setUname(newUser.getUname());
        oldUser.setNickName(newUser.getNickName());
        oldUser.setGroupId(newUser.getGroupId());
        oldUser.setHeadImg(newUser.getHeadImg());
        oldUser.setMobile(newUser.getMobile());
    }

}
